package com.github.cyf.desensition;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;

/**
 * @author chenyifan
 * @create 2024-05-08 21:37
 */
// ContextualSerializer：Jackson 提供的另一个序列化相关的接口，它的作用是通过字段已知的上下文信息定制 JsonSerializer。
public class DesensitizedInfoSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private DesensitizedType desensitizedType;
    private int startInclude;
    private int endExclude;

    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (value != null) {
            if (desensitizedType == null) {
                jsonGenerator.writeString(value);
            } else if (desensitizedType == DesensitizedType.CUSTOM) {
                jsonGenerator.writeString(DesensitizedUtil.desensitized(value, startInclude, endExclude));
            } else {
                jsonGenerator.writeString(DesensitizedUtil.desensitized(value, desensitizedType));
            }
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty property)  {
        if (property != null) {
            Desensitization desensitization = property.getAnnotation(Desensitization.class);
            if (desensitization != null) {
                this.desensitizedType = desensitization.type();
                this.startInclude = desensitization.startInclude();
                this.endExclude = desensitization.endExclude();
            }
        }
        return this;
    }
}
